package com.azt.front.action.enquiry;

import com.azt.api.pojo.Category;
import com.azt.api.pojo.ProRepository;
import com.azt.api.service.ProCategoryService;
import com.azt.api.service.ProRepositoryService;
import com.azt.front.action.BaseAction;
import com.azt.front.utils.ContextUtil;
import com.azt.model.AjaxJson;
import com.azt.provider.CategoryConstants;
import com.azt.utils.FreemarkerUtils;
import com.azt.utils.MyStringUtils;
import com.azt.utils.PasswordUtil;
import com.azt.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 选择系统
 * Created by 张栋 on 2016/11/911:16
 */
@Controller
@RequestMapping("/category")
public class ProCategoryAction extends BaseAction {

    @Autowired
    private ProCategoryService proCategoryService;

    @Autowired
    private ProRepositoryService repositoryService;


    /**
     * 系统选择弹窗
     * Created by 张栋 on 2016/11/9 11:14
     */
    @RequestMapping("/choose")
    public String companyInfo(ModelMap model) {
        //当前系统
        String current = RequestUtils.getString("current");
        String callback = RequestUtils.getString("callback");
        String hasearch = RequestUtils.getString("hasearch");
        model.put("hasearch",hasearch);


        model.put("current", current == null ? "" : current);
        model.put("callback",callback);
        boolean b =false;
        try {
            //预留接口用于手动生成,手动调用,不传参数时
            b = updateCategoryTemp((current == null && callback == null));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //
        if(current!=null && current.indexOf(",")!=-1){
            //有多个匹配时,取name,name存在时,先按name查
            String name = RequestUtils.getString(request, "name", null);
            if(name!=null){
                List<Integer> recats = new ArrayList<>();
                String trim = MyStringUtils.replaceBlank(name);
                String md5_16 = PasswordUtil.MD5_16(trim);
                List<ProRepository> repositoryBymd5 = repositoryService.getRepositoryBymd5(md5_16);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < repositoryBymd5.size(); i++) {
                    ProRepository proRepository = repositoryBymd5.get(i);
                    if(i!=0){
                        sb.append(",");
                    }
                    sb.append(proRepository.getPid());
                    recats.add(proRepository.getId());
                }
                current = sb.toString();
                if((!current.equals("")) && (current.indexOf(",")==-1)){
                    model.put("current", current);
                }
                model.put("recats",recats.isEmpty()?null:recats);
            }
            if((!current.equals("")) && (current.indexOf(",")!=-1)){
                // 显示的上下级关系
                List<String> mulitys = new ArrayList<>();
                List<Integer> firstCatids = new ArrayList<>();
                List<Integer> thirdCatids = new ArrayList<>();
                List<String> thirdName= new ArrayList<>();
                String[] split = current.split(",");
                for (String s : split) {
                    Category thirdCategory = CategoryConstants.categoryByid.get(s);
                    Category secondCategory = thirdCategory.getProCategory();
                    Category firstCategory = secondCategory.getProCategory();
                    mulitys.add(firstCategory.getName()+"---"+secondCategory.getName()+"---"+thirdCategory.getName());
                    firstCatids.add(firstCategory.getId());
                    thirdCatids.add(thirdCategory.getId());
                    thirdName.add(thirdCategory.getName());
                }
                model.put("mulitys",mulitys);
                model.put("firstCatids",firstCatids);
                model.put("thirdCatids",thirdCatids);
                model.put("thirdCatName",thirdName);
            }

        }
        if(b){
            return "category/temp_pro_choose_ategory";
        }else{
            List<Category> categorys = proCategoryService.getAllCategories();
            model.put("categorys", categorys);
            return "category/pro_choose_ategory_async";
        }

    }

    //删除一个仓库信息
    @RequestMapping("/del_repository")
    @ResponseBody
    public AjaxJson delRepository(){
        AjaxJson j = new AjaxJson();
        Integer repositoryid = RequestUtils.getInteger("repositoryid");
        ProRepository pro = repositoryService.getEntityById(repositoryid);
        repositoryService.deleteEntity(pro);
        return j;
    }



    String newtempname = "temp_pro_choose_ategory.html";
    String tempname = "pro_choose_ategory.html";
    volatile boolean creating =false;

    /**
     * 更新类目选择文件
     *
     *
     *
     * @author 张栋  2016年7月8日上午9:34:49
     */
    public boolean updateCategoryTemp(boolean auto) throws Exception {
        String tempath = ContextUtil.getSession().getServletContext().getRealPath("/WEB-INF/front/category");
        if(auto){//强制生成
            createHtml(tempath);
            return true;
        }
        //返回true时,带表有生成的文件,可以直接用,否则需要动态创建
        if (!proCategoryService.proCategoryTempAuotCreate(-1)) {

            //自动状态下,不存在就生成
            java.io.File file = new java.io.File(tempath + "/" + newtempname);
            if (file.exists()) {
                //存在则不生成
                return true;
            }else{
                createHtml(tempath);
                return false;
            }
        } else {
            //为true时需要生成
            //非自动情况,直接生成
            createHtml(tempath);
            return false;
        }

    }




    //简单同步,超高并发下还是会重复生成
    public void  createHtml(final String tempath){
        if(!creating){
            creating=true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<Category> categorys = proCategoryService.getAllCategories();
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("categorys", categorys);
                        FreemarkerUtils.createHtml(tempath, tempname, paramMap, newtempname);
                    } catch (Exception e) {
                        java.io.File file = new java.io.File(tempath + "/" + newtempname);
                        if (file.exists()) {
                            file.delete();
                        }
                    }finally {
                        creating=false;
                    }
                }
            }).start();
        }
    }

    @ResponseBody
    @RequestMapping("/find")
    public AjaxJson findCategory() {
        Integer id = getParaToInt("id");
        Integer pid = getParaToInt("pid");
        Integer cateType = getParaToInt("cateType");

        return AjaxJson.success().setObj(proCategoryService.findCategory(id, pid, cateType));
    }
}
